package com.it.reggie.utils;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.internal.OSSHeaders;
import com.aliyun.oss.model.CannedAccessControlList;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.StorageClass;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

/**
 * @author:cyh
 * @data:2022/12/21 10:39
 */
@Component
public class OssUtil {
    private static String aliDomain="https://reggie-dish-mage.oss-cn-hangzhou.aliyuncs.com/";
    //@Value("${oss.endpoint}")
    private static String endpoint="https://oss-cn-hangzhou.aliyuncs.com";
    //@Value("${oss.accessKeyId}")
    private static String accessKeyId="LTAI5tMw3KSFJWJjb27guwL6";
    //@Value("${oss.accessKeySecret}")
    private static String accessKeySecret="b1JPMMsCqqdUfBrCny14HbMTPCrRyx";
    //@Value("${oss.bucketName}")
    private static String bucketName="reggie-dish-mage";

    private static String folder="dishImages/";
    public static String uploadImage(MultipartFile file) throws IOException {
        //生成文件名
        //原始文件名
        String originalFilename = file.getOriginalFilename();
        //得到图片类型
        String fileType = originalFilename.substring(originalFilename.lastIndexOf("."));
        //使用UUID重新生成文件名，防止文件名称重复造成文件覆盖
        String fileName= UUID.randomUUID().toString()+fileType;

        //oos客户端对象
        OSS ossClient=new OSSClient(endpoint,accessKeyId,accessKeySecret);
        // 创建PutObjectRequest对象。
        PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, folder+fileName, new ByteArrayInputStream(file.getBytes()));
        //设置文件的存储类型和访问权限
        ObjectMetadata metadata = new ObjectMetadata();
        metadata.setContentType("image/jpg");
        metadata.setHeader(OSSHeaders.OSS_STORAGE_CLASS, StorageClass.Standard.toString());
        metadata.setContentDisposition("inline");
        metadata.setObjectAcl(CannedAccessControlList.PublicRead);
        putObjectRequest.setMetadata(metadata);
        // 上传字符串。
        ossClient.putObject(putObjectRequest);
        ossClient.shutdown();
        return aliDomain+folder+fileName;
    }
}
